﻿using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using SqlSugar;
using System.Data;

namespace BootstrapBlazor.OnlyServerZhongShun.Components.Pages.中顺
{
    public class ExportController : Controller
    {
        private readonly SqlSugarScope _SqlSugarScope;
        public ExportController(SqlSugarScope sqlSugarScope)
        {
            _SqlSugarScope = sqlSugarScope;
        }
        public IActionResult Index(string tableName)
        {
            DataTable dt = _SqlSugarScope.Ado.GetDataTable($"select * from {tableName}");
            var memoryStream = new MemoryStream();
            memoryStream.SaveAs(dt);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"{tableName}.xlsx"
            };
        }

        public IActionResult ExportBySql(string tableName, string sql)
        {
            DataTable dt = _SqlSugarScope.Ado.GetDataTable(sql);
            var memoryStream = new MemoryStream();
            memoryStream.SaveAs(dt);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"{tableName}.xlsx"
            };
        }
    }
}
